/*

Copyright (c) 2012 Al Vo. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Runtime.InteropServices;

using System.IO;

namespace XactiSource.Core.Windows.Controls
{

	[
	ToolboxBitmap( typeof( EmbeddedAppControl ), "UserControl.bmp" ),
	]
	public class EmbeddedAppControl : System.Windows.Forms.Panel
	{
		private const int WS_VISIBLE = 0x10000000;
		private const int GWL_STYLE = ( -16 );
		private const int SW_SHOWNORMAL = 1;
		private const int WM_CLOSE = 0x10;

		private IntPtr _AppPointer = IntPtr.Zero;
		private string _ApplicationName = null;
		private bool _RefreshRequired = true;

		/// <summary>
		/// Constructor
		/// </summary>
		public EmbeddedAppControl()
		{
		}

		#region DLLImport
		[DllImport( "user32.dll", EntryPoint = "GetWindowThreadProcessId", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall )]
		private static extern long GetWindowThreadProcessId( long hWnd, long lpdwProcessId );

		[DllImport( "user32.dll", SetLastError = true )]
		private static extern bool MoveWindow( IntPtr hwnd, int x, int y, int cx, int cy, bool repaint );

		[DllImport( "user32.dll", EntryPoint = "PostMessageA", SetLastError = true )]
		private static extern int PostMessage( IntPtr hWnd, int Msg, uint wParam, int lParam );

		[DllImport( "user32.dll", EntryPoint = "SetWindowLongA", SetLastError = true )]
		private static extern long SetWindowLong( IntPtr hwnd, int nIndex, int dwNewLong );

		[DllImport( "user32.dll", SetLastError = true )]
		private static extern long SetParent( IntPtr hWndChild, IntPtr hWndNewParent );

		[DllImport( "user32.dll" )]
		static extern bool ShowWindow( IntPtr hWnd, int nCmdShow );

		[DllImport( "user32.dll" )]
		private static extern bool IsWindowVisible( IntPtr hWnd );
		#endregion

		/// <summary>
		///  Application to embed.  Every time ApplicationName is set, it will refresh/reload the control.
		/// </summary>
		public string ApplicationName
		{
			get
			{
				return _ApplicationName;
			}
			set
			{
				_ApplicationName = value;
				_RefreshRequired = true;
				OnVisibleChanged( new EventArgs() );
			}
		}

		private void ClearHandle()
		{
			if ( _AppPointer != IntPtr.Zero )
			{
				PostMessage( _AppPointer, WM_CLOSE, 0, 0 );
				System.Threading.Thread.Sleep( 1000 );
				_AppPointer = IntPtr.Zero;
			}
		}

		#region Override Panel Functionality
		protected override void OnSizeChanged( EventArgs e )
		{
			this.Invalidate();
			base.OnSizeChanged( e );
		}

		protected override void OnVisibleChanged( EventArgs e )
		{
			if ( _RefreshRequired && !string.IsNullOrEmpty( _ApplicationName ) )
			{
				_RefreshRequired = false;
				ClearHandle();
				try
				{
					int counter = 0;
					var processStartInfo = new ProcessStartInfo( _ApplicationName );
					processStartInfo.WindowStyle = ProcessWindowStyle.Minimized;
					var process = Process.Start( processStartInfo );
					while ( process.MainWindowHandle == IntPtr.Zero )
					{
						if ( counter >= 300 ) throw new Exception( "Could not embed the started application." );
						System.Threading.Thread.Sleep( 10 );
						process.Refresh();
						counter++;
					}
					process.WaitForInputIdle();
					_AppPointer = process.MainWindowHandle;
				}
				catch ( Exception ex )
				{
					MessageBox.Show( ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error );
					return;
				}

				ShowWindow( _AppPointer, SW_SHOWNORMAL );
				SetParent( _AppPointer, this.Handle );
				SetWindowLong( _AppPointer, GWL_STYLE, WS_VISIBLE );
				MoveWindow( _AppPointer, 0, 0, this.Width, this.Height, true );
				
				this.Refresh();
			}
			base.OnVisibleChanged( e );
		}

		protected override void OnHandleDestroyed( EventArgs e )
		{
			ClearHandle();
			base.OnHandleDestroyed( e );
		}

		protected override void OnResize( EventArgs e )
		{
			if ( _AppPointer != IntPtr.Zero )
				MoveWindow( _AppPointer, 0, 0, this.Width, this.Height, true );
			base.OnResize( e );
		}
		#endregion
	}
}
